const express = require('express'),
  router = express.Router(),
  util = require("../util/util"),
  book = require("../model/book"),
  formidable = require('formidable'),
  fs = require('fs'),
  reObj = util.reObj;


/**
 * @function 添加校区信息
 * @author Eric
 * @date 2018-08-01
 * @param name,code,addr,area,status
 */
router.post('/add', (req, res) => {

    let id = util.randomString(8);
    let name=req.body.name;
    let queryparam = {
      //  id: id,
        name:name
    }
    book.findOrCreate({
        where: queryparam,
        defaults: req.body
    }).then(record => {
        if (record[1]) {
            res.send(reObj(0, '添加成功', record[0]))
        } else {
          //console.log("dddddddd:"+JSON.stringify(record))
            res.send(reObj(-1, '记录已存在',record[0]))
        }
    }).catch(err => {
        res.send(reObj(-1, '添加失败', err))
    });

})

/**
 * @function 编辑校区信息
 * @author Eric
 * @date 2018-08-01
 * @param id,name,code,addr,area,status
 */
router.post('/update', (req, res) => {
  let id = req.body.id
  let params = {
    id: id
  }

    book.update(req.body, {where: params}).then(record => {
        if (record[0] > 0) {
            console.log("record:"+JSON.stringify(record))
            res.send(reObj(0, '修改成功', record[0]))
        } else {
            res.send(reObj(-1, '无效的id', []))
        }
    }).catch(err => {
        res.send(reObj(-1, '修改失败', err))
    });

})

/**
 * @function 删除对应的会议数据
 * @author Eric
 * @date 2018-07-31
 * @param id
 */
router.post('/del', (req, res) => {
  let params = {
    id: req.body.id
  }

  book.destroy({where: params}).then(record => {
    if (record > 0) {
      res.send(reObj(0, '删除会议成功', record))
    } else {
      res.send(reObj(-1, '删除会议失败或此记录不存在', record))
    }
  }).catch(err => {
    res.send(reObj(-1, '删除会议失败', err))
  });
})

/**
 * @function 获取单个信息
 * @author Eric
 * @date 2018-08-01
 * @param meetingid
 */
router.post('/findone', async (req, res) => {
  let params = {}
  let id = req.body.id
  try {
    if (id) {
      params.id = id;
      let record=await book.findOne({where: params})
      let priceRecord=await price.findOne({where:{bookid:id,type:"1"}})      
    if (record) {
      let newRecord=JSON.parse(JSON.stringify(record))
      if(priceRecord)
      {
        newRecord.price=priceRecord.price
      }
      
      
      res.send(reObj(0, '获取信息成功', newRecord))
    } else {
      res.send(reObj(-1, '获取信息失败或此记录不存在', {}))
    }
    }
  } catch (error) {
    res.send(reObj(-1, '获取信息失败', error))
  }
  /* if (id) {
    params.id = id;

    book.findOne({where: params}).then(record => {
      if (record) {
        res.send(reObj(0, '获取信息成功', record))
      } else {
        res.send(reObj(-1, '获取信息失败或此记录不存在', {}))
      }
    }).catch(err => {
      res.send(reObj(-1, '获取信息失败', err))
    });
  } else {
    res.send(reObj(-1, 'id不能为空', []))
  } */
})


/**
 * @function 获取所有数据(支持分页，条件过滤)
 * @author Eric
 * @date 2018-07-31
 * @param page,pagerow,meetingname,meetingtype
 */
// router.post('/findall', (req, res) => {
//  /* let meetingname = req.body.meetingname || ''
//   let meetingtype = req.body.meetingtype || ''*/
//   let params = {}
//   let pagerow = parseInt(req.body.pagerow)
//   let page = parseInt(req.body.page)
//   //对页码进行容错
//   if (pagerow > 999) {
//     pagerow = 999
//   }
//   if (page == 0) {
//     page = 1
//   }

//   //筛选条件
// /*  if (meetingname) {
//     params.meetingname = {'$like': '%' + meetingname + '%'}
//   }
//   if (meetingtype) {
//     params.meetingtype = meetingtype
//   }*/


//   book.findAndCountAll({
//     order: "creattime DESC",
//     limit: pagerow || 100,
//     offset: parseInt(pagerow * (page - 1)) || 0,
//     where: req.body
//   }).then(record => {
//     if(record.count>0){
//       res.send(reObj(0, '获取数据成功', record.rows, record.count))
//     }
//     else
//     {
//       res.send(reObj(0, '没有符合条件的记录', record.rows, record.count))
//     }
    
//   }).catch(err => {
//     res.send(reObj(-1, '获取数据失败', err))
//   });
// })
router.post('/findall', (req, res) => {
  /* let meetingname = req.body.meetingname || ''
   let meetingtype = req.body.meetingtype || ''*/
   let params = req.body
   let pagerow = parseInt(req.body.pagerow)
   let page = parseInt(req.body.page)
   if(pagerow){
     delete params.pagerow;
   }
   if(page){
     delete params.page;
   }
   //对页码进行容错
   if (pagerow > 999) {
     pagerow = 999
   }
   if (page == 0) {
     page = 1
   }
 
 
   //筛选条件
 /*  if (meetingname) {
     params.meetingname = {'$like': '%' + meetingname + '%'}
   }
   if (meetingtype) {
     params.meetingtype = meetingtype
   }*/
 
   book.findAndCountAll({
     order: "creattime DESC",
     limit: pagerow || 100,
     offset: parseInt(pagerow * (page - 1)) || 0,
     where: params
   }).then(record => {
     if(record.count>0){
       res.send(reObj(0, '获取数据成功', record.rows, record.count))
     }
     else
     {
       res.send(reObj(0, '没有符合条件的记录', record.rows, record.count))
     }
     
   }).catch(err => {
     res.send(reObj(-1, '获取数据失败', err))
   });
 })
 
/**
 * @function 修改书籍封面
 * @author siwei
 * @date 2018-07-23
 * @param uuid,file(图片)
 */
 router.post('/upload', (req, res) => {
  /*1.创建表单*/
  let form = new formidable.IncomingForm();
  /*1.1设置上传图片放置的临时路径*/
  form.uploadDir = './public/images/';
    form.keepExtensions = true;
  /*2.使用表单解析对应的请求*/
  form.parse(req, (err, fields, files) => {
    console.log("file:"+JSON.stringify(files))
    res.set('Content-Type', 'text/html');
    if (err) {
      res.send(reObj(-1, '图片上传失败', err))
    } else {
      let newPath = `${__dirname}/../public/images/`;
       let newName = files.file.name;
   
      /*3.文件重命名到新路径*/
      fs.renameSync(files.file.path, newPath + newName);
      //res.send(newPath + newName)
      res.send(reObj(0, '图片上传成功','/images/' + newName))
     
    }
  })
})

module.exports = router;
